import { Component, OnInit, Host, ViewChild, ElementRef, ViewEncapsulation } from '@angular/core';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs/Observable';

import MousePosition from 'ol/control/mouseposition';
import ScaleLine from 'ol/control/scaleline';

import { OlState, MousePositionUpdate, viewSelector } from '../../../ngx-ol/store';

import { MapComponent } from '../../../ngx-ol/components/map/map.component';

@Component({
  selector: 'ege-map-information',
  templateUrl: './information.component.html',
  styleUrls: ['./information.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class InformationComponent implements OnInit {

  @ViewChild('mousePosition') mousePosition: ElementRef;
  @ViewChild('scaleLine') scaleLine: ElementRef;

  zoom$: Observable<number>;

  constructor(
    private olStore: Store<OlState>,
    @Host() protected map: MapComponent
  ) { }

  ngOnInit() {
    this.initMousePosition();
    this.initScaleLine();
    this.zoom$ = this.olStore.select(viewSelector.getViewZoom);
  }

  initMousePosition(): void {
    const instance = new MousePosition({
      target: this.mousePosition.nativeElement,
      className: 'mouse-position-content',
      projection: 'EPSG:4326',
      coordinateFormat: (position) => {
        const lng: number = Math.round(position[0]*10000)/10000;
        const lat: number = Math.round(position[1]*10000)/10000;
        this.olStore.dispatch(new MousePositionUpdate({lng, lat}));
        return [lng, lat];
      }
    });
    this.map.instance.addControl(instance);
  }

  initScaleLine(): void {
    const instance = new ScaleLine({
      className: 'scale-line-content',
      target: this.scaleLine.nativeElement
    });
    this.map.instance.addControl(instance);
  }


}
